<template>
  <!-- 流程定义 -->
  <div>
    <el-row>
      <el-col style="margin-right: 10px" class="content-left">
        <el-row class="handleBox">
          <el-col :span="18">
            <template>
              <el-button type="normal" @click="addFunc">新增</el-button>
              <el-button type="normal" @click="editFunc">编辑</el-button>
              <el-button type="normal" @click="copyFunc">复制</el-button>
              <el-button type="normal" @click="delFunc()">删除</el-button>
              <el-button type="normal" @click="enable()"
                >启动最新版本</el-button
              >
              <el-button type="normal" @click="toVersion()">版本管理</el-button>
            </template>
          </el-col>
          <el-col :span="6">
            <div class="handleIconBox">
              <!-- <el-popover
                placement="bottom"
                trigger="click"
                popper-class="icon_porper"
              >
                <div class="export_porper"> -->
                  <!-- 导出操作区域 -->
                  <!-- <el-button @click="exportExcel('userExport')"
                    >导出数据</el-button
                  >
                </div>
                <i
                  class="iconfont icon-export"
                  title="导出"
                  slot="reference"
                ></i>
              </el-popover> -->
              <!-- 导入 -->
              <!-- <el-popover
                placement="bottom"
                trigger="click"
                popper-class="icon_porper"
              >
                <div class="import_porper"> -->
                  <!-- 导入操作区域 -->
                  <!-- <el-upload
                    accept=".xls, .xlsx"
                    ref="upload"
                    :multiple="false"
                    :before-upload="beforeUpload"
                    :show-file-list="false"
                    action
                    :limit="1"
                    :http-request="uploadFile"
                  >
                    <el-button>导入数据</el-button>
                  </el-upload>
                </div>
                <i
                  class="iconfont icon-import"
                  title="导入"
                  slot="reference"
                ></i>
              </el-popover> -->
              <el-popover
                placement="bottom"
                trigger="click"
                popper-class="icon_porper"
              >
                <div class="search_porper">
                  <el-form
                    :model="searchForm"
                    ref="searchForm"
                    label-width="90px"
                    label-position="left"
                    size="mini"
                  >
                    <el-form-item label="流程名称：">
                      <el-input
                        v-model="searchForm.modelName"
                        style="width: 150px"
                      ></el-input>
                    </el-form-item>
                    <el-form-item label="流程编号：">
                      <el-input
                        v-model="searchForm.modelCode"
                        style="width: 150px"
                      ></el-input>
                    </el-form-item>
                  </el-form>
                  <div style="text-align: center; padding: 10px">
                    <el-button
                      size="mini"
                      @click="(searchForm.page = 1), searchFunc()"
                      >查询</el-button
                    >
                    <el-button size="mini" @click="searchClear">重置</el-button>
                  </div>
                </div>
                <i
                  class="iconfont icon-sousuo"
                  title="搜索"
                  slot="reference"
                ></i>
              </el-popover>
              <el-popover
                placement="bottom"
                width="150"
                trigger="click"
                popper-class="icon_porper"
              >
                <div class="operation_checkbox">
                  <el-checkbox-group v-model="checkList">
                    <el-checkbox
                      v-for="item in textData"
                      :label="item.label"
                      :key="item.prop"
                      >{{ item.label }}
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
                <i
                  class="iconfont icon-liebiaoshezhi"
                  title="列表设置"
                  slot="reference"
                ></i>
              </el-popover>
            </div>
          </el-col>
        </el-row>

        <el-table
          ref="multipleTable"
          :data="tableData"
          @row-click="authorizeFor"
        >
          <el-table-column
            width="55"
            type="selection"
            
          ></el-table-column>
          <el-table-column
            prop="modelName"
            label="流程名称 "
            v-if="columnState[0]"
            show-overflow-tooltip
          >
          </el-table-column>

          <el-table-column
            prop="modelCode"
            label="流程编号"
            v-if="columnState[1]"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop="lastUpdateTime"
            label="最后修改时间"
            sortable
            v-if="columnState[2]"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <div v-if="scope.row.lastUpdateTime">
                {{ timeFormat(scope.row.lastUpdateTime) }}
              </div>
              <div v-else>-</div>
            </template>
          </el-table-column>
          <el-table-column
            prop="description"
            label="描述"
            show-overflow-tooltip
            v-if="columnState[3]"
            :formatter="(row) => row.description || '-'"
          >
          </el-table-column>
        </el-table>
        <pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="searchForm.page"
          :page-size="searchForm.size"
          @refresh="searchFunc"
          :total="total"
        ></pagination>
      </el-col>
    </el-row>
    <!-- 流程定义弹窗 -->
    <el-dialog
      v-dialogDrag
      :title="saveTitles[saveFlg - 1]"
      :visible.sync="addOrEdit"
      width="50%"
    >
      <el-form
        :model="saveForm"
        ref="saveForm"
        label-width="110px"
        label-position="left"
        :rules="saveFormRules"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="流程编号：" prop="modelCode">
              <el-input
                v-model="saveForm.modelCode"
                maxlength="20"
                style="width: 80%"
                :disabled="saveFlg == 2"
                placeholder="请输入流程编号"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="流程名称：" prop="modelName">
              <el-input
                v-model="saveForm.modelName"
                style="width: 80%"
                maxlength="40"
                placeholder="请输入流程名称"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="备注：" prop="description">
              <el-input
                show-word-limit
                type="textarea"
                v-model="saveForm.description"
                maxlength="120"
                :rows="3"
                style="width: 80%"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="saveFunc">确 定</el-button>
        <el-button @click="addOrEdit = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 版本管理弹框 -->
    <el-dialog
      v-dialogDrag
      :title="'版本管理'"
      :visible.sync="versionVisible"
      width="60%"
    >
      <version-manage
        ref="version"
        :processDefCodeVersion="processDefCodeVersion"
      ></version-manage>
    </el-dialog>
  </div>
</template>
<script>
import versionManage from '@/views/workFlow/flowDefinition/versionManage'
import moment from "moment";
import { workflow } from "@/api/index";

export default {
  data() {
    return {
      processDefCodeVersion: "", // 传递的版本管理号
      exportIcon: true,
      importIcon: true,
      versionVisible: false,
      userName: "", //右侧用户名
      userDo: "授权角色", // 右侧用户行为
      userDoFlag: 0,
      addOrEdit: false, // 新增/编辑/查看弹窗
      isModuleData: false, //同步模块数据弹窗
      serachMore: false,
      isProConfig: false, //工程表配置弹窗
      saveFlg: 1, // 1:新增，2：编辑，3查看,
      saveTitles: ["新增流程定义", "编辑流程定义", "复制流程定义"],
      // 机构树
      orgList: [
        {
          value: "01",
          label: "一级机构",
          children: [{ value: "001", label: "二级机构" }],
        },
      ],
      statusList: [
        { value: "1", label: "已激活" },
        { value: "0", label: "已锁定" },
      ],
      moduleDataForm: {},
      // save表单机构树悬停提示
      saveOrgTip: "",
      searchForm: {
        modelCode: "",
        modelName: "",
        page: 1,
        size: 15,
      },
      total: 0,
      saveForm: {
        modelCode: "",
        modelName: "",
        description:"",
        lastVersion: 0,
        modelId: "",
        category:""
      },
      searchFF: {},
      saveFormRules: {
        modelCode: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          {
            pattern: /^[a-zA-Z][a-zA-Z0-9_!]{2,20}$/,
            message: "请输入3-20个以字母开头，字母、数字及_！",
            trigger: "blur",
          },
        ],
        modelName: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          {
            pattern: /^[\u4E00-\u9FA5A-Za-z0-9（）()\[\]【】{}]{1,15}$/,
            message: "只能输入1-15位的汉字、字母、数字或括号",
            trigger: "blur",
          },

        ],
        currencyFlag: [
          { required: true, message: "请选择主币种标志", trigger: "blur" },
        ],
      },
      checkList: [],
      // 列隐藏
      textData: [
        { label: "流程名称" },
        { label: "流程编号" },
        { label: "最后修改时间" },
        { label: "描述" },
      ],
      // 获取table的数据
      tableData: [],
      //编辑行内数据暂存，供判断表单状态
      editRow: {},
    };
  },
  components: {
    versionManage,
  },
  created() {
    this.reload()
    this.checkListInit();
    this.searchFunc();
  },
  computed: {
    columnState() {
      let arr = [],
        arr1 = this.textData,
        arr2 = this.checkList;
      for (let i = 0; i < arr1.length; i++) {
        let flg = false;
        for (let j = 0; j < arr2.length; j++) {
          if (arr1[i].label === arr2[j]) {
            flg = true;
          }
        }
        arr.push(flg);
      }
      return arr;
    },
  },
  mounted() {
  },
  watch: {
    addOrEdit() {
      // 窗口打开或关闭清除校验结果
      if (this.$refs.saveForm) {
        this.$refs.saveForm.clearValidate();
      }
    },
  },
  methods: {
    reload(){
      location.reload()
    },
    beforeUpload(){
      console.log('导入前')

    },
    uploadFile(){
      console.log('导入')
    },
    searchClear() {
      for (const key in this.searchForm) {
        this.searchForm[key] = "";
      }
      this.searchForm.page = 1;
      this.searchForm.size = 15;
    },
    checkListInit() {
      this.checkList = this.textData.map((v) => {
        return v.label;
      });
    },
    searchFunc() {
      let data = this.searchForm;
      workflow.queryModelForPage(data).then((res) => {
        this.tableData = res.datas.rows;
        this.total = res.datas.total
      });
    },
    // 版本管理分页查询
    searchFuncVersion() {},
    addFunc() {
      this.saveFlg = 1;
      for (let k in this.saveForm) {
        this.saveForm[k] = "";
      }
      this.addOrEdit = true;
    },
    editFunc() {
      this.saveFlg = 2;
      let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据进行修改");
      }
      let row = selection[0];
      let form = { ...row };
      this.editRow = form;
      this.saveForm = form;
      this.addOrEdit = true;
    },
    copyFunc() {
      this.saveFlg = 3;
      let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据");
      }
      let row = selection[0];
      let form = { ...row };
      this.editRow = form;
      this.saveForm = form;
      this.addOrEdit = true;
    },
    saveFunc() {
      this.$refs["saveForm"].validate((valid) => {
        if (valid) {
          let data = {
            ...this.saveForm,
          };
          if(this.saveFlg == '3'){
             workflow.processCopy(data).then((res) => {
            if (res.code == 200) {
              this.$message.success( res.message || "复制成功");
              this.addOrEdit = false;
              this.searchFunc();
            } else {
              this.$message.error(res.message || "保存失败");
            }
          });
            

          } else{
          workflow.saveProcessDef(data).then((res) => {
            if (res.code == 200) {
              this.$message.success("保存成功");
              this.addOrEdit = false;
              this.searchFunc();
            } else {
              this.$message.error(res.message || "保存失败");
            }
          });
          }
         
        }
      });
    },
    delFunc() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length < 1) {
        return this.$message.warning("请选择要删除的数据");
      }
      this.$confirm("您确定要删除选中数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let delFlag = true;
          let data = { ids: selection.map((v) => v.modelCode) };
          workflow.delProcessDefAllVersion(data).then((res) => {
            if (res.code == 200) {
              this.$message.success("删除成功");
              this.searchFunc();
            } else {
              this.$message.error(res.message || "删除失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 启动最新版本
    enable(data) {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length < 1) {
        return this.$message.warning("请选择流程");
      }
      this.$confirm(`您确定要启用该流程最新版本吗`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          if (selection.length > 1) {
            return this.$message.warning("请选择一条流程");
          }
          let data = {
            // processDesignId: selection[0].modelId,
            modelKey: selection[0].modelCode
          };
          workflow.startByLatestVersionKey(data).then((res) => {
            if (res.code == 200) {
              this.$message.success("启动成功");
              this.searchFunc();
            } else {
              this.$message.error(res.message || "启动成功");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    // 进入版本管理页面
    toVersion() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length < 1) {
        return this.$message.warning("请选择流程");
      }
      if (selection.length > 1) {
        return this.$message.warning("请选择一条流程");
      }
      this.versionVisible = true;
      this.processDefCodeVersion = selection[0].modelCode;
      setTimeout(()=>{
        this.$refs.version.searchFunc();
        this.$refs.version.checkListInit();
      },50)
      
    },
    // 导出
    exportFiles() {
      console.log("导出数据");
    },
    handleNodeClick() {
      let nodes = this.$refs.configTree.getCheckedNodes();
    },
    caliberProjectNameFormatter(row) {
      return row.caliberProject.caliberProjectName;
    },
    authorizeFor(row) {
      if (this.$refs.multipleTable) {
        this.$refs.multipleTable.clearSelection();
        this.$refs.multipleTable.toggleRowSelection(row, true);
      }
      this.userName = row.roleName;
    },
    // 重新加载
    reload() {
      this.isModuleData = true;
    },
    timeFormat(val) {
      if (val) return moment(val).format("YYYY-MM-DD HH:mm:ss");
      else return "";
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.searchForm.size = val;
      this.searchFunc();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.searchForm.page = val;
      this.searchFunc();
    },
  },
};
</script>

<style lang="scss" scoped>
.dialogSearchBox {
  header {
    text-align: center;
    span {
      margin: 0 20px;
    }
  }
}
</style>